<script setup>
import { ref, computed, onMounted, watch, reactive } from 'vue';
import {
    reqDormitory,
    reqDormitoryFloor,
    reqInquireStayNote
} from '@/api/teacher/record/stay';
import { showFailToast } from 'vant';
import todoListItem from '@/component/todoListItem.vue';

// 是否显示抽屉
const isShowDrawer = ref(false);

// 下拉加载
const load = () => {
    getRecordDormitory();
};

const activeName = ref('1');

// 是否显示加载中
const loading = ref(false);

// 是否提示todolist没有更多数据
const noMore = ref(true);

// 在加载时和没有数据的时候不能继续使用下拉加载
// (可以理解为在加载时和没多数据时不能使用load方法)
const disabled = computed(() => loading.value || noMore.value);

// 时间选项
const timeOption = [
    {
        value: 'thisWeek',
        label: '本周'
    },
    {
        value: 'lastWeek',
        label: '上周'
    },
    {
        value: 'thisMonth',
        label: '本月'
    },
    {
        value: '',
        label: '空(默认查询所有时间段)'
    }
];

// 宿舍选项
const dormitoryOption = ref([]);

// 楼层选项
const floorOption = ref([]);

// 表单数据
const stayNote = reactive({
    time: '',
    dormitory: '',
    floor: ''
});

// 表单验证规则
const rules = reactive({});

// 表单ref
const formRef = ref();

// 点击查询按钮
const inquire = async formEl => {
    if (!formEl) return;
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            isShowDrawer.value = false;
            list.value = [];
            pageNo = 1;
            await getRecordDormitory();
        } else {
            console.warn(fields);
        }
    });
};

// 获取宿舍
const getDormitoryOptions = async () => {
    try {
        const result = await reqDormitory();

        if (result.status == 200) {
            dormitoryOption.value = result.dataList;
            dormitoryOption.value.push({
                id: '',
                name: '空(默认选择全部)'
            });
        } else {
            throw new Error(result.statusText);
        }
    } catch (e) {
        showFailToast(e?.message || '请求宿舍列表失败');
    }
};

// 获取楼层
const getDormitoryFloorOption = async () => {
    try {
        const result = await reqDormitoryFloor(stayNote.dormitory);

        if (result.status == 200) {
            floorOption.value = result.dataList;
            floorOption.value.push({
                id: '',
                name: '空(默认选择全部)'
            });
        } else {
            throw new Error(result.statusText);
        }
    } catch (e) {
        showFailToast(e?.message || '请求宿舍楼层列表失败');
    }
};

let pageNo = 1;

// 获取留宿申请
const getRecordDormitory = async () => {
    noMore.value = false;
    loading.value = true;
    try {
        let time;

        if (stayNote.time) {
            time = getTime();
        }

        const result = await reqInquireStayNote({
            startTime: time?.startTime || null,
            endTime: time?.endTime || null,
            building: stayNote.dormitory || null,
            floor: stayNote.floor || null,
            states: ['4', '33'],
            pageNo,
            pageSize: 10
        });

        if (result.status == 200) {
            const dataList = result.dataList;

            if (dataList) {
                if (dataList.length < 5) {
                    noMore.value = true;
                }

                list.value.push(...dataList);
            } else {
                noMore.value = true;
            }
        } else {
            throw new Error(result.statusText);
        }

        pageNo++;
    } catch (e) {
        noMore.value = true;
        showFailToast(e?.message || '请求宿舍门号列表失败');
    }
    loading.value = false;
};

const list = ref([]);

/**
 * 通过timeOption获取时间
 * 假设今天是10月26日 -- 是星期四
 *  如果表单时间被选择的是'本周'
 *  - 那么返回 ['....-10-23 00:00:00', '....-10-29 23:59:59']
 *  被选择的是'上周'
 *  - 那么返回 ['....-10-16 00:00:00', '....-10-22 23:59:59']
 *  被选择的是'本月'
 *  - 那么返回 ['....-10-1 00:00:00',  '....-10-31 23:59:59']
 */
const getTime = () => {
    const today = new Date();
    switch (stayNote.time) {
        case 'thisWeek':
            const startOfWeek = new Date(today);
            startOfWeek.setDate(today.getDate() - startOfWeek.getDay() + 1);

            const endOfWeek = new Date(today);
            endOfWeek.setDate(today.getDate() + (7 - endOfWeek.getDay()));

            return {
                startTime: formatTime(startOfWeek),
                endTime: formatTime(endOfWeek, true)
            };
        case 'lastWeek':
            const startOfLastWeek = new Date(today);
            startOfLastWeek.setDate(
                today.getDate() - startOfLastWeek.getDay() - 6
            );

            const endOfLastWeek = new Date(today);
            endOfLastWeek.setDate(today.getDate() - endOfLastWeek.getDay());

            return {
                startTime: formatTime(startOfLastWeek),
                endTime: formatTime(endOfLastWeek, true)
            };
        case 'thisMonth':
            const startOfThisMonth = new Date(
                today.getFullYear(),
                today.getMonth(),
                1
            );
            const nextMonth = new Date(
                today.getFullYear(),
                today.getMonth() + 1,
                1
            );
            const endOfThisMonth = new Date(nextMonth.getTime() - 1);
            return {
                startTime: formatTime(startOfThisMonth),
                endTime: formatTime(endOfThisMonth, true)
            };
    }
};

// 格式化时间
const formatTime = (date, flag) => {
    let month = date.getMonth() + 1;
    month = month.toString().padStart(2, '0');
    let day = date.getDate();
    day = day.toString().padStart(2, '0');
    let time = `${date.getFullYear()}-${month}-${day} `;
    if (flag) {
        time += '23:59:59';
    } else {
        time += '00:00:00';
    }
    return time;
};

// 当宿舍改变时楼层也更着改变
watch(
    () => stayNote.dormitory,
    () => {
        stayNote.floor = '';
        getDormitoryFloorOption();
    }
);

onMounted(() => {
    getDormitoryOptions();
});
</script>

<template>
    <div class="container">
        <el-collapse v-model="activeName" class="collapse">
            <el-collapse-item name="1">
                <template #title>
                    <span class="collapse__title"> 筛选 </span>
                </template>
                <el-form :model="stayNote" :rules="rules" ref="formRef">
                    <el-form-item label="时间" prop="time">
                        <el-select
                            v-model="stayNote.time"
                            size="large"
                            class="leaveType input"
                        >
                            <el-option
                                v-for="option in timeOption"
                                :key="option.value"
                                :label="option.label"
                                :value="option.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="宿舍" prop="dormitory">
                        <el-select
                            v-model="stayNote.dormitory"
                            size="large"
                            class="leaveType input"
                            placeholder="请选择宿舍 (如果为空默认选择全部)"
                        >
                            <el-option
                                v-for="option in dormitoryOption"
                                :key="option.id"
                                :label="option.name"
                                :value="option.id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="楼层" prop="floor">
                        <el-select
                            v-model="stayNote.floor"
                            size="large"
                            class="leaveType input"
                            :disabled="!floorOption.length"
                            :placeholder="
                                !floorOption.length
                                    ? '请先选择宿舍 (如果为空默认选择全部)'
                                    : '请选择楼层 (如果为空默认选择全部)'
                            "
                        >
                            <el-option
                                v-for="option in floorOption"
                                :key="option.id"
                                :label="option.name"
                                :value="option.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-form>
                <el-button type="primary" @click="inquire(formRef)">
                    查询
                </el-button>
            </el-collapse-item>
        </el-collapse>
        <div class="content">
            <ul
                class="todoList"
                v-infinite-scroll="load"
                :infinite-scroll-disabled="disabled"
                infinite-scroll-distance="10"
            >
                <todoListItem :list="list"></todoListItem>
                <div v-if="loading" class="loading" v-loading="loading"></div>
                <div v-if="noMore" class="no-more">没有更多数据了</div>
            </ul>
        </div>
    </div>
</template>

<style scoped lang="scss">
.container {
    height: 100vh;
    display: flex;
    flex-direction: column;
}

.input {
    width: 100%;
}

.collapse {
    margin: 0 20rem;
    z-index: 999;

    &__title {
        font-size: 18rem;
        font-weight: 600;
    }
}

.content {
    position: relative;
    flex: 1;
    font-size: 10rem;
    overflow: auto;
}

.todoList {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin-top: 20rem;
    overflow: auto;
    padding: 5rem 20rem 0;

    .loading {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 10rem;
        font-size: large;
        margin-top: 20rem;
        background-color: #bbb;
    }

    .no-more {
        width: 100%;
        height: 10rem;
        margin-top: 20rem;
        font-size: 14rem;
        color: #999;
        text-align: center;
    }
}
</style>
